<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-02 19:42:06
 * @LastEditTime: 2023-01-04 15:49:35
 * @LastEditors: sunkaiyuan sunkaiyuan@namenode.com
 * @Description: 
 */

namespace App\Repositories;

use App\Models\Unit;
use App\Models\Dic;

class UnitRepository extends Repositories
    {

    protected $relation_models = ['creator', 'updator', 'firstunit', 'lastunit'];
    public function boot(Unit $model)
        {
        $this->model = $model;
        }


    public function list()
        {
        return $this->model->get();
        }

    public function delete($ids)
        {
        return $this->whereIn("id", $ids)->get()->filter(function ($v)
            {
            return $v->delete();
            });
        }
    protected function getRate($uunit1_id, $uunit2_id)
        {
        $coefficient = -1;
        if ($uunit1_id != $uunit2_id) {
            $coefficient_data = $this->whereFirstunit_id($uunit1_id)->whereLastunit_id($uunit2_id)->first();
            if ($coefficient_data) {
                $coefficient = $coefficient_data->coefficient;
                }
            else {
                $coefficient_data = $this->whereFirstunit_id($uunit2_id)->whereLastunit_id($uunit1_id)->first();
                if ($coefficient_data)
                    $coefficient = 1 / $coefficient_data->coefficient;
                }
            }
        else {
            $coefficient = 1;
            }
        if ($coefficient == -1) {
            $uunit1 = Dic::whereCode("unit")->whereKey($uunit1_id)->first();
            $uunit2 = Dic::whereCode("unit")->whereKey($uunit2_id)->first();
            fail("【{$uunit1->name}】与【{$uunit2->name}】未建立转换关系！");
            }
        return $coefficient;
        }
    }